package com.emre.daoGenerator.beanRowMapper;

import java.io.File;
import java.io.IOException;

import com.emre.daoGenerator.GlobalConstants;
import com.emre.daoGenerator.bean.BeanDefinition;
import com.emre.daoGenerator.utils.JavaCodeWriter;

public class BeanRowMapperClassGenerator 
{
	private BeanDefinition beanDefinition;
	
	private String path;
	
	public BeanRowMapperClassGenerator(BeanDefinition beanDefinition, String path)
	{
		this.beanDefinition = beanDefinition;
		this.path = path;
	}
	
	public File generate() throws IOException
	{
		JavaCodeWriter writer = new JavaCodeWriter(path + beanDefinition.getName() + "RowMapper.java");
		
		String packageDeclaration = "package " + GlobalConstants.topLevelPackageName + "." +GlobalConstants.beanRowMapperPackageName + ";";
		writer.write(packageDeclaration, 0);
		writer.writeEmptyLine();
		
		writer.write(GlobalConstants.beanRowMapperClassImportStatements, 0);
		
		String beanExtractorClass = beanDefinition.getName() + "Extractor";
		
		writer.write("import " + GlobalConstants.topLevelPackageName + "." + GlobalConstants.beanExtractorPackageName + "." + beanExtractorClass + ";", 0);
		writer.writeEmptyLine();

		String classDeclaration = "public class " + beanDefinition.getName() + "RowMapper implements RowMapper";
		writer.write(classDeclaration, 0);
		writer.write("{", 0);
		
		String mapRowMethodDeclaration = "public Object mapRow(ResultSet rs, int rowNum) throws SQLException";
		writer.write(mapRowMethodDeclaration, 1);
		writer.write("{", 1);
		
		String beanExtractorDeclaration = beanExtractorClass + " extractor = new " + beanExtractorClass + "();";
		writer.write(beanExtractorDeclaration, 2);
		
		writer.write("return extractor.extractData(rs);", 2);
				
		writer.write("}", 1);
		
		writer.write("}", 0);
						
		writer.close();
		
		return writer.getFile();
	}
}

